# -*- coding: utf-8 -*-
import datetime
import time
import os
import sys
#import xlwt #需要的模块
import xlsxwriter #需要的模块
import pyparsing as pp #字符串分割
 
path = r"你的输入路径"
def txt2xls(fp, file):
    if os.path.exists(fp):
        print ("------>>", fp)
        f = open(fp)
        #wb = xlwt.Workbook()
        #ws1 = wb.add_sheet("Sheet1")
        fileName = r"你的输出路径" + "\\" + str(file[-40:-4]) + '.xlsx'
        wb = xlsxwriter.Workbook(fileName)
        ws1 = wb.add_worksheet("Sheet1")
 
        i = 0
        for line in f.readlines():
            j = 0
            csv_line = pp.delimitedList(pp.Word(pp.printables), delim=',').addParseAction(pp.tokenMap(lambda s: s.strip('"')))
            csv_line = csv_line * 2#输出一列可以把这一行删了
            arrData = csv_line.parseString(line).asList()
            for item in arrData:
                try:
                    item = item.strip()
                except UnicodeDecodeError:
                    print (i, j, item)
                    ws1.write(i, j, "NULL")
                else:
                    ws1.write(i, j, item)
                j = j + 1
            i = i + 1
        f.close()
        #wb.save("F:\Alice\Template1" + "\\" + str(file[-40:-4]) + '.xls')
        wb.close()
 
 
def getfiles():
    files = os.listdir(path)
    for file in files:
        print (file)
        print (file[-40:-4])
        fp = path + "\\" + file
        print (fp)
        txt2xls(fp, file)
 
if __name__ == '__main__':
    getfiles()
    print ("处理完毕，按回车键结束程序。")